#!/bin/sh
#
# Copyright (C) 2017 ~ 2018 Deepin Technology Co., Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# Update grub menu options on x86 based platformats like:
#  * Set grub menu timeout;
#  * Remove windows menu item;
#  * Update grub background image;

if ! is_x86; then
  return 0
fi

GRUB_CONF=/etc/default/grub
GRUB_NEED_UPDATE=false

GRUB_TIMEOUT=$(installer_get "grub_timeout")
if [ -n "${GRUB_TIMEOUT}" ]; then
  # Update timeout of boot menu.
  if grep -q "^GRUB_TIMEOUT=" "${GRUB_CONF}"; then
    sed -i "${GRUB_CONF}" -e "s/^\(GRUB_TIMEOUT\)=.*/\1=${GRUB_TIMEOUT}/g"
  else
    echo "GRUB_TIMEOUT=${GRUB_TIMEOUT}" >> "${GRUB_CONF}"
  fi
  GRUB_NEED_UPDATE=true
fi

GRUB_BLOCK_WINDOWS=$(installer_get "grub_block_windows")
if [ x"${GRUB_BLOCK_WINDOWS}" = "xtrue" ]; then
  # Remove windows menu item from boot menu by disable os-prober from finding
  # Windows partitions.
  # Remove windows probes from os-prober script list.
  [ -f /usr/lib/os-probes/mounted/20microsoft ] && \
    rm /usr/lib/os-probes/mounted/20microsoft
  [ -f /usr/lib/os-probes/mounted/efi/20microsoft ] && \
    rm /usr/lib/os-probes/mounted/efi/20microsoft
  GRUB_NEED_UPDATE=true
fi

# deepin-fallback need jpg file, and imagemagisk does not work for sw platform,
# cannot conver png to jpg. So modify the requirements of oem.
OEM_GRUB_BACKGROUND="${OEM_DIR}/grub.jpg"
GRUB_BACKGROUND=/boot/grub/themes/deepin/background_source
GRUB_BACKGROUND_FAILBACK=/boot/grub/themes/deepin-fallback/background.jpg
if [ -f "${OEM_GRUB_BACKGROUND}" ]; then
  # Update background of boot menu by overwriting old background image.
  install -m644 -v "${OEM_GRUB_BACKGROUND}" "${GRUB_BACKGROUND}"
  install -m644 -v "${OEM_GRUB_BACKGROUND}" "${GRUB_BACKGROUND_FAILBACK}"

  GRUB_NEED_UPDATE=true
fi

if [ x${GRUB_NEED_UPDATE} = "xtrue" ]; then
  update-grub
fi

return 0
